<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="cpHeadItemList"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">调拨信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem label="调拨类型" name="transferType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.baseMatrType}"
                          :disabled="!propParent.cpFormNew"
                          help-tip="保存后不可修改"
                          @change="transferTypeChange"
                          ref="transferType"
          />

          <customFormItem
            label="调入仓库" name="toWarehouseName" :parent="_self" :form="form"
            :disabled="!propParent.cpFormNew"
            :type="constCommon.formItemType.slot.name"
            @focusTo="$refs.toWarehouseName.focus()"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="false"
                :idNe="form.fromWarehouseId"
                v-model="form.toWarehouseId"
                :valueDisplay="form.toWarehouseName"
                @change="toWarehouseChange"
                :disabled="!propParent.cpFormNew"
                ref="toWarehouseName"
              />
            </template>
          </customFormItem>

          <customFormItem
            label="调出仓库" name="fromWarehouseName" :parent="_self" :form="form"
            :type="constCommon.formItemType.slot.name"
            @focusTo="$refs.fromWarehouseName.focus()"
          >
            <template #content>
              <warehouseSelect
                :flagCenter="true"
                :idNe="form.toWarehouseId"
                v-model="form.fromWarehouseId"
                :valueDisplay="form.fromWarehouseName"
                @change="fromWarehouseChange"
                :disabled="!propParent.cpFormNew"
                ref="fromWarehouseName"
              />
            </template>
          </customFormItem>


          <customFormItem label="消耗方式" name="settlementType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.settlementType}"
                          help-tip="保存后不可修改<br>出库消耗:出到二级库算二级库成本<br>扫码消耗:库存转移到对应二级库，之后走扫码计费"
                          :disabled="cpSettlementTypeDisabled"
          />

          <customFormItem label="单据来源" name="sourceType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectStatic.name"
                          :config="{options: distTransferSourceTypeList}"
                          :disabled="!propParent.cpFormNew"
                          help-tip="保存后不可修改<br>手动单据:手动增加拣货明细<br>自动科室需求:由科室需求创建的调拨单<br>
                          手工科室需求:需要先创建科室需求，再拣货"
          />

          <customFormItem label="调拨单号" name="busKey" :parent="_self" :form="form"
                          :type="constCommon.formItemType.staticHtml.name"
                          :config="{defaultValue: '自动获取'}"
          />
          <customFormItem label="调拨日期" name="busDate" :parent="_self" :form="form"
                          disabled
          />
          <customFormItem label="调拨人" name="busUser" :parent="_self" :form="form" disabled  />
          <customFormItem label="金额" name="amount" :parent="_self" :form="form" disabled  />

          <customFormItem label="备注" name="remark"  :parent="_self" :form="form" width2x/>
        </template>
      </customForm>

      <div id="box-demand" class="box-title" v-show="cpIsDemand">拣货单</div>
      <data-view
        ref="childRequired"
        propViewKey="wm_transfer_demand"
        :propFlowKey="propParent.propFlowKey"
        :propInitData="form"
        :propParentPage="_self"
        :propAutoFetchData="false"
        @view-ready="afterLoad"
        @edit-input="rowEditInput"
        @customSelectFocus="transferDemandCustomSelectFocus"
        :propsDisableDbClick = "true"
        :propHideFlowSelect = "true"
        :propParentData="propParent.viewFormData"
        class=" data-view-nojump"
        v-show="cpIsDemand"
        :propTableHide="propParent.cpFormNew"
        propTableHideMsg="请先保存主单据再操作"
        @extra-button-click="extraButtonClickDemand"
      />

      <div id="box-dtl" class="box-title">调拨明细</div>
      <customTooltip title="title" v-show="cpIsAddDtl">
        <template #title>
          选择库存或者扫描相关标签码
        </template>
        <template #content>
          <FortenScan ref="scan" propPlaceholder="扫描唯一码进行拣货或者取消拣货" style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px" @after-scan="barCodeScan" propType="uniqueCode"/>

          <customButton title="选择库存" theme="primary" class="btn-scan"
                        @click="
                        utilSelect.stockMore(
                          selectChangeStock, form.fromWarehouseId, cpFlagOmoc, true, true, form.transferType
                          , null, null, null, null, null, cpFlagMagnum
                        )"
          />
        </template>
      </customTooltip>
      <data-view ref= "childDataView"
     :propHideFlowSelect = "true"
       propViewKey="wm_transfer_item_out"
       propViewForm="wm/transfer-item/detail.vue"
       :propFlowKey="propParent.propFlowKey"
       :propInitData="form"
       :propParentPage="_self"
     :propParentData="propParent.viewFormData"
       :propAutoFetchData="false"
       :propNoEditRow="true"
       :propHideColumns="hideColumns"
       :propsDisableDbClick="true"
       @after-delete="loadDemand"
       :propTableHide="!cpIsShowDtl"
       propTableHideMsg="制单或者拣货中才可操作"
       class="data-view-inlinebtn"
       @afterTableDataChange="afterTableDataChange"
       :propIsColumnEdit="propIsColumnEdit"
      />
    </div>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import warehouseSelect from '@/components/custom/bus/select/warehouseSelect.vue'
export default {
  data() {
    return {
      form: {},
      viewData: {},
      txtScan: '',
      formDisabled: false,
      defaultSourceType: 'manual',
      settlementTypeOut: 'out',
      settlementTypeUsed: 'used',
      collapse: ['1', '2'], //默认显示
      distTransferSourceTypeList: [
        {
          value: 'manual',
          label: '手动单据',
          remark: '无需求拣货，可以直接进行拣货，不做任何限制',
          disabled: false
        },
        {
          value: 'dept_apply_auto',
          label: '自动科室需求',
          remark: '需求自动转换的单据，拣货必须在需求范围内',
          disabled: true
        },
        {
          value: 'dept_apply',
          label: '手工科室需求',
          remark: '需要先创建需求，再进行拣货',
          disabled: false
        }
      ]
    }
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String,
    propParam: Object
  },
  components: {
    customAnchor,
    warehouseSelect
  },
  computed: {
    // 是否是试剂
    cpIsReagent() {
      return this.form.transferType && this.form.transferType == 'reagent'
    },
    // 是否有需求
    cpIsDemand() {
      return this.form.sourceType && this.form.sourceType != 'manual'
    },
    // 是否可以添加明细
    cpIsAddDtl() {
      return this.form.flowStatus == 'start' || this.form.flowStatus == 'picking'
    },
    // 是否显示明细
    cpIsShowDtl() {
      return this.form.id
    },
    // 一物一码类型
    cpFlagOmoc() {
      if (this.form.settlementType == this.constCommon.dictType.settlementTypeOut) {
        return false
      }
      return ''
    },
    // 库存筛选类型
    cpFlagMagnum() {
      if (this.form.settlementType == this.constCommon.dictType.settlementTypeUsed) {
        return 0
      }
      return ''
    },
    // 标题
    cpHeadItemList() {
      if (this.cpIsDemand) {
        return [
          { name: 'box-base', title: '调拨信息' },
          { name: 'box-demand', title: '拣货单' },
          { name: 'box-dtl', title: '调拨明细' },
        ]
      }
      return [
        { name: 'box-base', title: '调拨信息' },
        { name: 'box-dtl', title: '调拨明细' },
      ]
    },
    cpStockQueries() {
      let wrapper = this.$newWrapper()
      wrapper.eq('warehouseId', this.form.fromWarehouseId)
        .eq('flagUniqueCode', 1)
        .ge('packageQty', 0)
        .eq('lockQty', 0)
      if (this.strings.isNotBlank(this.form.transferType)) {
        wrapper.eq('matrBaseType', this.form.transferType)
      }
      if (this.form.settlementType == this.settlementTypeOut) { //出库结算
        wrapper.ne('flagOmoc', 1).ne('flagStockReagent', 1)
      }
      return wrapper
    },
    cpRequiredVisible() {
      let rows0 = 0
      if (this.$refs.childRequired != null) {
        rows0 = this.$refs.childRequired.getRows0().length
      }
      return rows0 > 0 || this.form.flowStatus == 'start'
    },
    cpChildVisible() {
      return this.formDisabled &&  this.form.flowStatus != 'start' && this.form.flowStatus != 'submit'
    },
    cpRequiredSpan() { //计算需求单宽度
      if (!this.cpRequiredVisible) {
        return 0
      }
      if (this.form.flowStatus == 'start' || this.form.flowStatus == 'submit') {
        return 24
      }
      return 9
    },
    cpChildSpan() { //计算调拨单明细宽度
      return 24 - this.cpRequiredSpan
    },
    rtDisable() {
      return !(this.form.flowStatus == 'picking' || this.form.flowStatus == 'start')
    },
    hideColumns() {
      return this.form.transferType != 'reagent' ? ['flagStockReagent'] : []
    },
    // 消耗类型是否禁用
    cpSettlementTypeDisabled() {
      return !this.propParent.cpFormNew || this.utils.isBaseTypeLom(this.form.transferType)
    }
  },
  methods: {
    // 加载需求
    loadDemand() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('transferId', this.form.id)
      } else {
        queryWrapper.eq('transferId', -1)
      }
      this.$refs.childRequired.setQueryWrapper(queryWrapper)
    },

    // 加载明细
    loadDtl() {
      if (!this.cpIsShowDtl) {
        return
      }
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('transferId', this.form.id)
      } else {
        queryWrapper.eq('transferId', -1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },
    // 调出仓库选择
    fromWarehouseChange(row) {
      this.$set(this.form, 'fromWarehouseId', row.id)
      this.$set(this.form, 'fromWarehouseName', row.name)
    },
    // 调入仓库选择
    toWarehouseChange(row) {
      this.$set(this.form, 'toWarehouseId', row.id)
      this.$set(this.form, 'toWarehouseName', row.name)
      this.$set(this.form, 'deptIdTo', row.deptId)
      this.$set(this.form, 'deptNameTo', row.deptName)
    },
    //扫码SN或RFID
    barCodeScan(txtScan) {
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/transfer_item/scan', {autoUnlock: true, 'transferId': this.form.id, 'uniqueCode': txtScan, 'fromWarehouseId': this.form.fromWarehouseId}).then(
        resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.afterTableDataChange()
            this.loadDtl()
          }
          this.utilVue.loadHide()
        }
      )
    },
    fetchData() {
      this.loadDemand()
      this.loadDtl()
    },
    //库存选择后
    selectChangeStock(rows) {
      //转换成transferItem
      rows.forEach(row => {
        row.transferId = this.form.id
        row.stockId = row.id
        row.id = null
      })

      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/transfer_item/addBySelect', rows).then(resp => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          if (resp.msg) {
            this.utilMessage.success(resp.msg, 2000)
          }
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },
    async afterLoad() {
    },
    //批量添加需求明细
    addDemandBatch(rows) {
      let saveData = []
      for (let i = 0; i < rows.length; i += 1) {
        saveData.push({
          transferId: this.form.id,
          matrId: rows[i].matrId,
          matrName: rows[i].matrId,
        })
      }

      //批量添加
      this.utilVue.loadShow(true)
      this.$ajax.post('/wm/transfer_demand/addDtlBatch', saveData).then(resp => {
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
        }
        this.utilVue.loadHide()
        this.loadDemand()
      })
    },
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    rowEditInput({row, column}) {
      if (column.property == 'billPackageQty') {
        this.$set(row, 'billSkuQty', this.utilNum.toFixed(row.billPackageRate * row.billPackageQty))
        this.$set(row, 'billAmount', this.utilNum.toFixed(row.billSkuQty * row.skuPrice))
      }
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
      this.loadDemand()
    },

    // 需求选择
    transferDemandCustomSelectFocus(column, row) {
      // 选择商品
      if (column.name == 'matrName') {
        this.utilSelect.matrMore(
          this.addDemandBatch
        )
      }
      // 包装名称
      if (column.name == 'billPackageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitDemandSelect, row.matrId, true)
      }
    },

    // 需求单位选择后
    packageUnitDemandSelect(row) {
      // 当前选中行
      let currentRow = this.$refs.childRequired.getCurrentRow()
      this.$set(currentRow, 'billPackageUnit', row.unit)
      this.$set(currentRow, 'billPackageRate', row.packageRate)
      this.$set(currentRow, 'billSkuQty', this.utilNum.toFixed(currentRow.billPackageRate * currentRow.billPackageQty))
      this.$set(currentRow, 'billAmount', this.utilNum.toFixed(currentRow.billSkuQty * currentRow.skuPrice))
    },
    extraButtonClickDemand({button, data, index}) {
      let buttonKey = button.key
      if (buttonKey === 'printDtl') { // 打印
        let param = {
          'that': this, //当前调用对象
          configList: [ //打印配置，可以多个
            {
              //打印配置
              printBusType: 'printTransferDemand', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
              //主单据数据或者数据查询配置
              formData: this.form, //数据对象
              formDataId: this.form.id,
            }
          ]
        }
        global.utilPrint.openFormPrint(param)
      }
    },

    // 过滤编辑列
    propIsColumnEdit(column) {
      if (this.form.settlementType == this.constCommon.dictType.settlementTypeOut && ['packageQty'].includes(column.name)) {
        return true
      }
      return false
    },
    transferTypeChange() {
      if (this.utils.isBaseTypeLom(this.form.transferType)) {
        this.$set(this.form, 'settlementType', this.constCommon.dictType.settlementTypeOut)
      }
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          let getCurrentWarehouse = this.utils.getCurrentWarehouse()

          if (getCurrentWarehouse.warehouseId) {
            if (getCurrentWarehouse.flagCenter) {
              this.$set(this.form, 'fromWarehouseId', getCurrentWarehouse.warehouseId)
              this.$set(this.form, 'fromWarehouseName', getCurrentWarehouse.warehouseName)
            }
          }
          if (this.strings.isNotBlank(this.utils.getCurrentWarehouse().applyWarehouseId)) {
            // this.$set(this.form, 'toWarehouseId', this.utils.getCurrentWarehouse().applyWarehouseId)
            // this.$set(this.form, 'toWarehouseName', this.utils.getCurrentWarehouse().applyWarehouseName)
          }

          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDateTimePattern))
          this.$set(this.form, 'type', this.constCommon.dictType.wmInOrderTypeOutShift) //默认为手动配送出库
          this.$set(this.form, 'sourceType', this.defaultSourceType) //默认为手动配送出库
          this.$nextTick(() => {
            this.$refs.transferType.focus()
          })
        }

        this.loadDtl()
        this.loadDemand()
      },
      afterSave: () => {  },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey, thiz, buttonCode) => {
        if (buttonCode == 'cancelPicking') {
          this.$refs.childDataView.fetchData()
        }
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'printTransfer') { //打印明细
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'printTransfer', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        } else if (buttonKey == 'printTransferSum') { //打印汇总
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'printTransferSum', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      },
    })
  }
}
</script>
